import { ChatMessage } from "@/utils/Message";
import { useChatStore } from "@/stores";
import { storeToRefs } from "pinia";

let websocket: any = null;
let rec: any;

function creatWebSocket(wsUrl: string) {
    // 判断当前浏览器是否支持WebSocket
    if ("WebSocket" in window) {
        console.log("当前浏览器支持 WebSocket");
    } else if ("MozWebSocket" in window) {
        console.log("当前浏览器支持 MozWebSocket");
    } else {
        console.log("当前浏览器不支持 WebSocket");
    }
    try {
        init(wsUrl); // 初始化websocket连接
    } catch (e) {
        console.log("尝试创建连接失败");
        restConnection(wsUrl); // 如果无法连接上 webSocket 那么重新连接！可能会因为服务器重新部署，或者短暂断网等导致无法创建连接
    }
}


const init = (url: string) => {
    websocket = new WebSocket(url)
    websocket.onopen = WebSocketOpen;
    websocket.onclose = WebSocketClose;
    websocket.onmessage = (e: MessageEvent<any>) => {
        WebSocketMessage(e);

    }
}

const MessageSend = (senderId: string, receiverId: string, content: string, status: number) => {
    let chatMessage = new ChatMessage();
    chatMessage.senderId = senderId;
    chatMessage.receivedId = receiverId;
    chatMessage.content = content;
    chatMessage.chatId = "0";
    chatMessage.status = status;
    chatMessage.sendDate = new Date();
    websocket.send(JSON.stringify(chatMessage));
}

const WebSocketOpen = () => {
    console.log("链接成功")
}

const WebSocketClose = () => {
    console.log("链接断开")
}

const WebSocketMessage = (e: MessageEvent<any>) => {
    console.log("回调函数", e)
    const chatStore = useChatStore()
    const { setMsg } = chatStore;
    const { msg } = storeToRefs(chatStore)
    setMsg(e.data)
    return e;
}

const restConnection = (url: string) => {
    console.log("尝试重新连接");
    // if (store.state.isConnected) return; // 如果已经连上就不在重连了
    rec && clearTimeout(rec);
    rec = setTimeout(function () {
        init(url);
        // 延迟5秒重连  避免过多次过频繁请求重连
    }, 5000);
}

export {
    creatWebSocket,
    WebSocketOpen,
    WebSocketClose,
    WebSocketMessage,
    MessageSend
}